package com.eric.windows.imgDispose;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.EViewGroup;

/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> Eric
 * <h3>Date</h3> 2017/8/26 17:26
 * <h3>Copyright</h3> Copyright (c)2017 Shenzhen TLIT  Co., Ltd. Inc. All rights reserved.
 */
@EViewGroup
public class WaterfallLayout extends ViewGroup {
    /**每行列数*/
    private int columns = 3;
    /** 水平间距*/
    private int vSpace = 20;
    /** 垂直间距*/
    private int hSpace = 20;
    /**每个子View的宽度*/
    private int childWidth = 0;
    /**储存每列的高度*/
    private int top[];

    public WaterfallLayout(Context context) {
        super(context);
    }

    public WaterfallLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WaterfallLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public WaterfallLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @AfterInject
    void initData(){
        top = new int[columns];
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        childWidth = (sizeWidth - (columns - 1) * hSpace) / columns;
        //控件总宽度
        int wrapWidth;
        int childCount = getChildCount();
        if (childCount < columns) {//子view的数目小于列数
            wrapWidth = childCount * childWidth + (childCount - 1) * hSpace;
        } else {
            wrapWidth = sizeWidth;
        }

        clearTop();
        for (int i = 0; i < childCount; i++) {
            View child = this.getChildAt(i);
            int childHeight = child.getMeasuredHeight() * childWidth / child.getMeasuredWidth();
            int minColum = getMinHeightColum();
            top[minColum] += vSpace + childHeight;
        }

        //控件总高度
        int wrapHeight;
        wrapHeight = getMaxHeight();
        setMeasuredDimension(widthMode == MeasureSpec.AT_MOST ? wrapWidth : sizeWidth, wrapHeight);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        clearTop();
        for (int i = 0; i < childCount; i++) {
            View child = this.getChildAt(i);
            //得到当前要摆放图片的高度
            int childHeight = child.getMeasuredHeight() * childWidth / child.getMeasuredWidth();
            //得到最短的列，准备将这个控件摆放在这个列中
            int minColum = getMinHeightColum();
            // 因为通过getMinHeightColum()得到的是当前最短列的索引，因为索引是从0开始的，所以，假设我们当前最短的是第三列，
            // 所以通过getMinHeightColum()得到的值是2；因为每个图片都是由图片本身和中间的间距组成，
            // 所以当前控件的left值就是2*（childWidth + hSpace）
            int tleft = minColum * (childWidth + hSpace);
            //top[minColum]就是当前要摆放图片的top值
            int ttop = top[minColum];
            //right就是left加上图片的宽度
            int tright = tleft + childWidth;
            //加上图片的自身高度就是bottom值
            int tbottom = ttop + childHeight;
            //更新当前列的高度
            top[minColum] += vSpace + childHeight;
            child.layout(tleft, ttop, tright, tbottom);
        }

    }

    /**
     *
     *
     *  首先，每次在计算高度之前，我们应该先把top[]数组清空，以防上次的数据影响这次的计算
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2017/8/28,10:19
     * <h3>UpdateTime</h3> 2017/8/28,10:19
     * <h3>CreateAuthor</h3> Eric
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     */
    private void clearTop() {
        for (int i = 0; i < columns; i++) {
            top[i] = 0;
        }
    }

    /**
     *
     * 获取最长列的高度
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2017/8/28,10:36
     * <h3>UpdateTime</h3> 2017/8/28,10:36
     * <h3>CreateAuthor</h3> Eric
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @return
     */
    private int getMaxHeight() {
        int maxHeight = 0;
        for (int i = 0; i < columns; i++) {
            if (top[i] > maxHeight) {
                maxHeight = top[i];
            }
        }
        return maxHeight;
    }


    /**
     *
     * @return 获取最短列的索引
     */
    private int getMinHeightColum() {
        int minColum = 0;
        for (int i = 0; i < columns; i++) {
            if (top[i] < top[minColum]) {
                minColum = i;
            }
        }
        return minColum;
    }



    public interface OnItemClickListener {
        void onItemClick(View v, int index);
    }


    public void setOnItemClickListener(final OnItemClickListener listener) {
        for (int i = 0; i < getChildCount(); i++) {
            final int index = i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(v, index);
                }
            });
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }



}
